// 2pages/login/login.js
let app = getApp();
import { loginApi, getMobilePhoneApi, getTokenApi } from "../../api/index.js";
let timeId = null;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    paddingTop: app.globalData.paddingTop,
    code: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    const code = await this.getWxCode();
    this.setData({ code });
    let token = wx.getStorageSync("token");
    let isLogout = wx.getStorageSync("isLogout");
    if (token) {
      wx.switchTab({
        url: "/pages/index/index",
      });
      return;
    } else if (isLogout != true) {
      this.getToken();
    }
  },
  onShow() {},
  onUnload() {
    clearTimeout(timeId);
  },

  //   跳转注册页
  bindRegistered() {
    wx.navigateTo({
      url: "/pages/register/register",
    });
  },
  // 获取微信code
  getWxCode() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: (res) => {
          let code = res.code;
          resolve(code);
        },
        fail: (err) => {
          reject(err);
        },
      });
    });
  },

  // 获取token
  async getToken() {
    try {
      const code = await this.getWxCode();
      const { data: res } = await getTokenApi({ code });
      wx.showToast({ title: "登录成功", icon: "none" });
      wx.setStorageSync("token", res.data.token);
      wx.setStorageSync("userId", res.data.userId);
      wx.setStorageSync("parkId", res.data.parkId);
      timeId = setTimeout(() => {
        wx.switchTab({
          url: "/pages/index/index",
        });
      }, 1000);
    } catch (error) {
      if (error.data.desc === "请授权手机号") {
        wx.hideToast();
        return;
      }
    }
  },

  //授权手机号
  async getPhoneNumber(e) {
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      const { encryptedData, iv } = e.detail;
      wx.checkSession({
        success: async () => {
          // console.log("session_key 未过期");
        },
        fail: async () => {
          const code = await this.getWxCode();
          this.setData({ code });
        },
        complete: async () => {
          let params = { code: this.data.code, encryptedData, iv };
          this.setData({
            params,
          });
          try {
            const { data: res } = await getMobilePhoneApi(params);
            wx.showToast({ title: "登录成功", icon: "none" });
            wx.setStorageSync("token", res.data.token);
            wx.setStorageSync("userId", res.data.userId);
            wx.setStorageSync("parkId", res.data.parkId);
            timeId = setTimeout(() => {
              wx.switchTab({
                url: "/pages/index/index",
              });
            }, 1000);
          } catch (error) {
            // console.log(error);
            getApp().showToast("网络异常,请重试!");
          }
        },
      });
    }
  },
  /**
   * 右上角分享功能
   */
  onShareAppMessage: function (res) {
    return {
      title: "",
      path: "/pages/index/index",
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      },
    };
  },
});
